<?php
/**
 * @package    com_puser 
 */

defined('_JEXEC') or die;

require_once(OC_App::getAppPath('company') . "/lib/helper.php");

/**
 * Registration controller class for Users.
 */
class PCompanyModelSubAccounts extends JModelLegacy
{
   public function hasUser($uid='') {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo(); 
      $query = "SELECT COUNT(*) FROM *PREFIX*users AS u " . 
               " LEFT JOIN *PREFIX*users_extended AS ue ON ue.uid=u.uid " . 
               " WHERE deleted=0 AND u.uid=" . $db->quote($uid) . " AND ue.owner = " . $db->quote($user->id); 

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadResult() > 0 ? true: false; 
   }

   public function hasGroup($gname='') {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo(); 
      $query = "SELECT COUNT(*) FROM *PREFIX*groups_custom " . 
               " WHERE groupname = " . $db->quote($gname) . " AND owner = " . $db->quote($user->id); 

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadResult() > 0 ? true: false; 
   }

   public function getGroups() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo(); 

      $query = "SELECT * FROM *PREFIX*groups_custom WHERE owner='' or owner=" . $db->quote($user->id)  . 
               " ORDER BY isadmin DESC, groupname ASC";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }

   public function getUserGroups($uid='') {
      $user = PFactory::getMasterUser();

      $db = PFactory::getDbo();

      $query = "SELECT b.groupname FROM *PREFIX*group_user_custom AS a " . 
               " LEFT JOIN *PREFIX*groups_custom AS b ON b.gid=a.gid" . 
               " WHERE a.uid=" . $db->quote($uid) . " AND (b.owner='' OR b.owner=" . $db->quote($user->id) .")" .  
               " ORDER BY b.isadmin DESC, b.groupname ASC";

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList(null, "groupname");
   }

   public function addGroups($groups=array()) {

      if(!PSession::checkToken('post')) {
         $this->setError('登录已失效，请重新登录');
         return false;
      }

      if(empty($groups))
         return true; 

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo(); 

      $query = "SELECT groupname FROM *PREFIX*groups_custom WHERE owner='' OR owner=" . $db->quote($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $clist = $db->loadAssocList(null, "groupname"); 

      /* only insert new list */
      if($clist)
         $groups = array_diff($groups, $clist); 

      if(empty($groups))
         return true; 

      $values = array();
      foreach($groups as $group) {
         if(strlen(trim($group)) <= 0)
            continue; 
         $values[] = "(" . $db->quote($group) . ", " . $db->quote($user->id) . ")"; 
      }

      
      $query = "INSERT IGNORE INTO *PREFIX*groups_custom (`groupname`, `owner`) VALUES " . 
               implode(",", $values); 

      $db->setQuery(PUtil::replaceOCPrefix($query));

      if(!$db->execute()) {
         $this->setError("添加分组失败！");
         return false; 
      }

      return true; 
   }

   public function deleteGroup($group='') {
      if(empty($group))
         return true; 

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "DELETE FROM *PREFIX*groups_custom WHERE groupname=" . $db->quote($group) . " AND owner=" . $db->quote($user->id); 
      
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute(); 
      return true; 
   }


   public function usersInGroup($group='') {
      if(empty($group))
         return array();

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT a.uid FROM *PREFIX*group_user_custom AS a " .
               " LEFT JOIN *PREFIX*groups_custom AS b ON b.gid=a.gid " .
               " WHERE b.groupname=" . $db->quote($group) .
               " AND (b.owner='' OR b.owner=" . $db->quote($user->id) . ")";

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }

   public function userInGroup($uid='', $group='') {
      if(empty($group))
         return false;

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT COUNT(*) FROM *PREFIX*group_user_custom AS a " . 
               " LEFT JOIN *PREFIX*groups_custom AS b ON b.gid=a.gid " . 
               " WHERE a.uid=" . $db->quote($uid) . " AND b.groupname=" . $db->quote($group) . 
               " AND (b.owner='' OR b.owner=" . $db->quote($user->id) . ")";

      $db->setQuery(PUtil::replaceOCPrefix($query));
      $result = $db->loadResult(); 

      return $result > 0 ? true: false; 
   }

   public function addUserToGroup($uid='', $groups=array()) {
      if(empty($groups))
         return true; 

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $values = array();
      foreach($groups as $group) {
         if(strlen(trim($group)) <= 0)
            continue;
         $values[] = $db->quote($group); 
      }
      
      $query = "SELECT gid FROM *PREFIX*groups_custom WHERE groupname IN (" . implode(",", $values) . ") AND (owner='' OR owner=" . $db->quote($user->id) . ")"; 
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $gids = $db->loadAssocList(null, "gid"); 
      if(empty($gids))
         return true; 

      $values = array();
      foreach($gids as $gid) {
         $values[] = "(" . $db->quote($gid) . ", " . $db->quote($uid) . ")"; 
      }

      $query = "INSERT IGNORE INTO *PREFIX*group_user_custom (gid, uid) VALUES " . implode(", ", $values); 
      
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if(!$db->execute()) {
         $this->setError("添加用户到分组失败！");
         return false; 
      }

      return true;
   }

   public function removeUserFromGroup($uid='', $group='') {
      if(empty($group))
         return false;

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "DELETE FROM *PREFIX*group_user_custom " . 
               " WHERE uid=" . $db->quote($uid) . 
               " AND gid = (SELECT gid FROM *PREFIX*groups_custom WHERE groupname=" . $db->quote($group) . "
                            AND (owner='' OR owner=" . $db->quote($user->id) . "))"; 

      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
      return true; 
   }

   public function removeUserGroups($uid='') {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "DELETE FROM *PREFIX*group_user_custom " .
               " WHERE uid=" . $db->quote($uid);

      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
      return true;
   }

   public function removeUserShares($uid='') {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "DELETE FROM *PREFIX*share " .
               " WHERE share_with=" . $db->quote($uid);

      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
      return true;

   }

   public function getUsers() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT DISTINCT u.displayname, ue.* " . 
               " FROM *PREFIX*users_extended AS ue " . 
               " LEFT JOIN *PREFIX*users AS u ON u.uid=ue.uid " . 
               " WHERE deleted=0 AND ue.owner = " . $db->quote($user->id) . " ORDER BY ue.createDate DESC"; 

      /* try to load from cache */
      $cache = CacheHelper::getCache('app_company');
      // get cached data now 
      $data = $cache->call(array($this, '_getUsers'), $query);

      // Event Driven Cache/Object Caching
      // there are the tables which we need to invoke cache cleaning triggers when tables are changed by user - Event Driven Cache/Object Caching
      CacheHelper::setTriggers($user->id, $cache, array('*PREFIX*users_extended'));
      
      return $data; 
   }
   
   public function _getUsers($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }
   
   public function getUser($uid) {
      if (empty($uid))
         return false;
      
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
   
      $query = "SELECT DISTINCT u.displayname, ue.* " .
               " FROM *PREFIX*users_extended AS ue " .
               " LEFT JOIN *PREFIX*users AS u ON u.uid=ue.uid " .
               " WHERE deleted=0 AND ue.owner = " . $db->quote($user->id) . " AND u.uid=" . $db->quote($uid);
   
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObject();
   }
   
   public function getAssignedJobs($uid) {
      if (empty($uid))
         return null;
   
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
       
      $query = "SELECT jj.id, jj.job_title FROM *PREFIX*hr_jobmanager AS hj
                LEFT JOIN *PREFIX*users_extended AS ue ON ue.uid=hj.manager
                LEFT JOIN #__jobs_job AS jj ON jj.id=hj.jobid WHERE jj.is_trashed=0 AND jj.system=0 AND ue.block=0 AND ue.deleted=0 AND jj.is_active='y' AND jj.employer_id=" . $user->id . " AND ue.uid=" . $db->quote($uid);
       
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList();
   }

   public function searchUsers($search=null, $limit=5) {
      if(!$search)
         return null; 

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT DISTINCT b.*" .
               " FROM *PREFIX*user_ownership AS a " .
               " LEFT JOIN *PREFIX*users AS b ON b.uid=a.uid " .
               " WHERE a.owner = " . $db->quote($user->id) .
               " AND b.displayname LIKE " . $db->quote('%'. $search . '%') . 
               " ORDER BY CASE WHEN b.displayname LIKE " . $db->quote($search . ' %') . " THEN 0
                              WHEN b.displayname LIKE " . $db->quote($search .'%') . " THEN 1
                              WHEN b.displayname LIKE " . $db->quote('% ' . $search . '%') . " THEN 2
                              ELSE 3
                         END,  b.displayname " . 
               " LIMIT " . $limit;

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }

   public function searchGroups($search=null, $limit=5) {
      if(!$search)
         return null;

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT * FROM *PREFIX*groups_custom " . 
               " WHERE (owner='' or owner=" . $db->quote($user->id)  . ')' . 
               " AND groupname LIKE " . $db->quote('%'. $search . '%') .   
               " ORDER BY CASE WHEN groupname LIKE " . $db->quote($search . ' %') . " THEN 0
                              WHEN groupname LIKE " . $db->quote($search .'%') . " THEN 1
                              WHEN groupname LIKE " . $db->quote('% ' . $search . '%') . " THEN 2
                              ELSE 3
                         END, isadmin DESC, groupname ASC LIMIT " . $limit;

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }

  public function searchUserGroups($uid='', $search=null, $limit=5) {
      $user = PFactory::getMasterUser();

      $db = PFactory::getDbo();

      $query = "SELECT b.* FROM *PREFIX*group_user_custom AS a " .
               " LEFT JOIN *PREFIX*groups_custom AS b ON b.gid=a.gid" .
               " WHERE a.uid=" . $db->quote($uid) . " AND b.owner=" . $db->quote($user->id) .
               " AND b.groupname LIKE " . $db->quote('%'. $search . '%') .   
               " ORDER BY CASE WHEN b.groupname LIKE " . $db->quote($search . ' %') . " THEN 0
                              WHEN b.groupname LIKE " . $db->quote($search .'%') . " THEN 1
                              WHEN b.groupname LIKE " . $db->quote('% ' . $search . '%') . " THEN 2
                              ELSE 3
                         END, b.isadmin DESC, b.groupname ASC LIMIT " . $limit ;

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }
   
   public function isDeletedUser($uid) {
      if (empty($uid))
         return false;
      
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $query = "SELECT COUNT(*) FROM *PREFIX*users AS u " .
               " LEFT JOIN *PREFIX*users_extended AS ue ON ue.uid=u.uid " .
               " WHERE deleted=1 AND u.uid=" . $db->quote($uid) . " AND ue.owner = " . $db->quote($user->id);
   
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadResult() > 0 ? true: false;
   }
   
   public function getUserPermissions($uid) {
      if (empty($uid))
         return 0;
      
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $query = "SELECT permissions FROM *PREFIX*users_extended WHERE uid=" . $db->quote($uid) . " AND owner=" . $db->quote($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadResult();
   }
   
   public function setUserPermissions($uid, $permissions) {
      if (empty($uid))
         return false;
   
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $query = "UPDATE *PREFIX*users_extended SET permissions=" . $permissions .
               " WHERE uid=" . $db->quote($uid) . " AND owner=" . $db->quote($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
     
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($uid, array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove($user->id, array('*PREFIX*users_extended'));

      return true;
   }
   
   public function createUserExtended($data) {
      if (empty($data) || !isset($data['uid'])) 
         return false;
      
      $db = PFactory::getDbo();
      $query = "INSERT IGNORE INTO *PREFIX*users_extended (uid, note, permissions, owner, createDate) 
                VALUES (" . $db->quote($data['uid']) . ", " . $db->quote($data['note']) . ", " . $data['permissions'] . ", " . PFactory::getMasterUser()->id . ", UTC_TIMESTAMP())";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      
      // create saved folder
      $query = "INSERT IGNORE INTO *PREFIX*hr_resume_folder (folder_name, owner, system) VALUES ('我的收藏', " . $db->quote($data['uid']) . ", 1)";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      
      $this->updateSubaccountsNum();
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($data['uid'], array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove(PFactory::getMasterUser()->get('id'), array('*PREFIX*users_extended'));
      return true;
   }
   
   public function updateUserExtended($data) {
      if (empty($data) || !isset($data['uid']))
         return false;
      
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      
      /* Deprecated code
      $query = "SELECT block FROM *PREFIX*users_extended WHERE uid=" . $db->quote($data['uid']) . " AND owner=" . $db->quote($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $block = $db->loadResult();
      if ($block && ($data['permissions'] & PERMISSION_JOB_ADMIN_ALL || $data['permissions'] & PERMISSION_JOB_ADMIN_ASSIGNED)) {
         $this->setError("已停用账号不能分配职位管理权限！");
         return false;
      }
      */
      
      $sql = "";
      if (isset($data['deleted'])) {
         $sql .= ", deleted=" . intval($data['deleted']);
      }
   
      $query = "UPDATE *PREFIX*users_extended SET note=" . $db->quote($data['note']) . ", permissions=" . $data['permissions'] . $sql . " WHERE uid=" . $db->quote($data['uid']);
      $db->setQuery(PUtil::replaceOCPrefix($query));
   
      if (!$db->execute())
         return false;

      $this->updateSubaccountsNum();
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($data['uid'], array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove($user->id, array('*PREFIX*users_extended'));
   
      return true;
   }
   
   public function saveJobManager($uid, $permissions, $assignedjobs = array()) {
      if (empty($uid) || empty($permissions))
         return false;
   
      $db = PFactory::getDbo();
      
      if(!($permissions & PERMISSION_JOB_ADMIN_ALL) && !($permissions & PERMISSION_JOB_ADMIN_ASSIGNED)) {
         $query = "DELETE FROM *PREFIX*hr_jobmanager WHERE manager=" . $db->quote($uid);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute())
            return false;
         
         // Event Driven Cache/Object Caching - clear any cache related to affected tables 
         CacheHelper::triggerRemove(PFactory::getMasterUser()->get('id'), array('*PREFIX*hr_jobmanager'));

         return true;
      }
      
      $user = PFactory::getMasterUser();
      
      $query = "SELECT hj.jobid FROM *PREFIX*hr_jobmanager AS hj
                LEFT JOIN *PREFIX*users_extended AS ue ON ue.uid=hj.manager
                LEFT JOIN #__jobs_job AS jj ON jj.id=hj.jobid WHERE ue.block=0 AND ue.deleted=0 AND jj.is_active='y' AND jj.employer_id=" . $user->id . " AND ue.uid=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $curJobidsArray = $db->loadAssocList('', 'jobid');
      $curJobidsArray = $curJobidsArray ? $curJobidsArray: array();
      
      $addJobidsArray = array();
      if($permissions & PERMISSION_JOB_ADMIN_ALL) {
         /* deserted code
         $query = "SELECT COUNT(*) FROM *PREFIX*users_extended AS ue
                   WHERE ue.block=0 AND ue.deleted=0 AND ue.permissions & " . $db->quote(PERMISSION_JOB_ADMIN_ASSIGNED) . " AND ue.owner=" . $user->id . " AND ue.uid!=" . $db->quote($uid);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if($db->loadResult()) {
            $this->setError("请解除其他子账号的职位管理权限，再授予全部职位管理权限！");
            return false;
         }
         */
         
         $query = "SELECT id FROM #__jobs_job WHERE is_active='y' AND employer_id=" . $user->id;
         $db->setQuery($query);
         $allJobidsArray = $db->loadAssocList('', 'id');
         $addJobidsArray = array_diff($allJobidsArray, $curJobidsArray);
      } elseif ($permissions & PERMISSION_JOB_ADMIN_ASSIGNED) {
         /* deserted code
         $query = "SELECT COUNT(*) FROM *PREFIX*users_extended AS ue
                   WHERE ue.block=0 AND ue.deleted=0 AND ue.permissions & " . $db->quote(PERMISSION_JOB_ADMIN_ALL) . " AND ue.owner=" . $user->id . " AND ue.uid!=" . $db->quote($uid);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if($db->loadResult()) {
            $this->setError("请解除其他子账号的全部职位管理权限，再授予指定职位管理权限！");
            return false;
         }
         
         if (!empty($assignedjobs)) {
            $query = "SELECT COUNT(*) FROM *PREFIX*hr_jobmanager AS hj
                      LEFT JOIN *PREFIX*users_extended AS ue ON ue.uid=hj.manager
                      WHERE ue.block=0 AND ue.deleted=0 AND ue.owner=" . $user->id . " AND ue.uid!=" . $db->quote($uid) . " AND hj.jobid IN (" . implode(",", $assignedjobs) . ")";
            $db->setQuery(PUtil::replaceOCPrefix($query));
            if($db->loadResult()) {
               $this->setError("所选职位包含已指定职位，请解除其他子账号对相关职位的管理权限，再授予指定职位管理权限！");
               return false;
            }
         }
         */
         
         if (empty($assignedjobs)) {
            $this->setError("请至少分配一个指定职位！");
            return false;
         }
         
         $query = "SELECT id FROM #__jobs_job WHERE is_active='y' AND system=1 AND employer_id=" . intval($user->id);
         $db->setQuery($query);
         $nojob = $db->loadResult();
         $addJobidsArray = array_diff($assignedjobs, $curJobidsArray);
         if(!empty($nojob)){
            array_push($addJobidsArray, $nojob);
         }
         $delJobidsArray = array_diff($curJobidsArray, $assignedjobs);
         if(!empty($delJobidsArray)) {
            $query = "DELETE FROM *PREFIX*hr_jobmanager WHERE manager=" . $db->quote($uid) . " AND jobid IN (" . implode(",", $delJobidsArray) . ")";
            $db->setQuery(PUtil::replaceOCPrefix($query));
            if (!$db->execute())
               return false;
         }
      }
      
      if(!empty($addJobidsArray)) {
         $values = array();
         foreach ($addJobidsArray as $jobid) {
            $values[] = "(" . intval($jobid) . ", " . $db->quote($uid) . ")";
         }
      
         $query = "INSERT IGNORE INTO *PREFIX*hr_jobmanager (jobid, manager) VALUES " . implode(",", $values);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute())
            return false;
      }

      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($uid, array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove($user->id, array('*PREFIX*hr_jobmanager'));
  
      return true;
   }
   
   public function removeUser($uid) {
      if (empty($uid))
         return false;

      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT ue.lastvisitDate FROM *PREFIX*users AS u " .
               " LEFT JOIN *PREFIX*users_extended AS ue ON ue.uid=u.uid " .
               " WHERE u.uid=" . $db->quote($uid) . " AND ue.owner = " . $db->quote($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $deleteRecord = isNullDate($db->loadResult()) ? true : false;
      
      // for nerver login account, we delete record directly, else we just change flag status
      if ($deleteRecord) {
         if(!OC_User::deleteUser($uid))
            return false;
         
         $query = "DELETE FROM *PREFIX*users_extended WHERE uid=" . $db->quote($uid);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute())
            return false;
      } else {
         $query = "UPDATE *PREFIX*users_extended SET deleted=1 WHERE uid=" . $db->quote($uid);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute())
            return false;
      }
      
      $query = "DELETE FROM *PREFIX*hr_jobmanager WHERE manager=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      
      $query = "DELETE rff.* FROM *PREFIX*hr_resume_folder_files AS rff
                LEFT JOIN *PREFIX*hr_resume_folder rf ON rf.folder_id=rff.folder_id WHERE rf.owner=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      
      $query = "DELETE FROM *PREFIX*hr_resume_folder WHERE owner=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
   
      $query = "DELETE FROM *PREFIX*share WHERE share_with=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      
      // remove subaccount folder on disk
      $datadir = getUserDataDir($user->id);
      $extdir = getUserExtDir($user->id);
      $dir = JPath::clean(OC::$SERVERROOT."/data".$datadir."/company/".$extdir.'/'.$uid);
      if(is_dir($dir) && basename($dir) == $uid) {
         JFolder::delete($dir);
      }

      $this->updateSubaccountsNum();
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($uid, array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove($user->id, array('*PREFIX*users_extended', '*PREFIX*hr_jobmanager'));

      // Get all the parent object id related to affected user for cache clean use
      $query = "SELECT DISTINCT a.parent
         FROM *PREFIX*calendar_interview_events a
         LEFT JOIN *PREFIX*calendar_objects b ON b.id = a.objectid
         LEFT JOIN *PREFIX*calendar_calendars c ON c.id = b.calendarid
         WHERE c.userid = ".$db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($db->useLastConnection($query)));
      $parents = $db->loadAssocList('','parent');

      // Delete calendar and object related tables
      /*$query = "DELETE co, cfa, cie, cod, cof, cir
         FROM *PREFIX*calendar_calendars cc
         LEFT JOIN *PREFIX*calendar_objects co ON co.calendarid = cc.id
         LEFT JOIN *PREFIX*calendar_feedback_answer cfa ON cfa.objectid = co.id
         LEFT JOIN *PREFIX*calendar_interview_events cie ON cie.objectid = co.id
         LEFT JOIN *PREFIX*calendar_objects_details cod ON cod.objectid = co.id
         LEFT JOIN *PREFIX*calendar_offer cof ON cof.objectid = co.id
         LEFT JOIN *PREFIX*calendar_interview_result cir ON cir.last_offer_objectid = co.id
         WHERE cc.userid = ".$db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;*/

      // Clean calendar app list view and calendar view cache
      CacheHelper::triggerRemove($user->id, array('*PREFIX*calendar_calendars', '*PREFIX*calendar_objects', '*PREFIX*calendar_interview_events', '*PREFIX*calendar_objects_details', '*PREFIX*calendar_interview_result', '*PREFIX*calendar_offer', '*PREFIX*calendar_feedback_answer'));
      // Clean each object related preview or edit view data cache
      foreach ($parents as $k => $objectid) {
         CacheHelper::triggerRemove($user->id, array('*PREFIX*calendar_objects-'.$objectid, '*PREFIX*calendar_interview_events-'.$objectid, '*PREFIX*calendar_objects_details-'.$objectid, '*PREFIX*calendar_interview_result-'.$objectid, '*PREFIX*calendar_offer-'.$objectid, '*PREFIX*calendar_feedback_answer-'.$objectid));
      }

      return true;
   }
   
   public function switchSubAccount($uid, $block = 0) {
      if (empty($uid))
         return false;
      
      if (!$block) {
         $userQuota = PCompanyHelper::getUserQuota();
         if (!isDevMode() && $userQuota['num_subaccounts'] >= $userQuota['quota']['subaccount_max'] && PCompanyHelper::checkQuotaEnable()) {
            $this->setError('您的子账号数目已达上限，不能启用该账号');
            return false;
         }
      }
      
      $user = PFactory::getMasterUser();
      
      $db = PFactory::getDbo();
      $query = "UPDATE *PREFIX*users_extended SET block=" . intval($block) . " WHERE uid=" . $db->quote($uid) . " AND owner=" . $db->quote($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));
   
      if (!$db->execute())
         return false;
      
      /* Deprecated code
      if ($block) {
         $query = "DELETE FROM *PREFIX*hr_jobmanager WHERE manager=" . $db->quote($uid);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute())
            return false;
         
         $permissions = PERMISSION_VIEW_ALL | PERMISSION_VIEW_SHARED;
         $query = "UPDATE *PREFIX*users_extended SET permissions=" . $permissions .
                  " WHERE uid=" . $db->quote($uid) . " AND owner=" . $db->quote($user->id);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute())
            return false;
      }
      */
      
      $this->updateSubaccountsNum();
   
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($uid, array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove($user->id, array('*PREFIX*users_extended'));
      return true;
   }
   
   public function setJobManager($jobid, $uid) {
      if (empty($jobid) || empty($uid)) {
         $this->setError("系统错误");
      }
      
      if(!PSession::checkToken('post')) {
         $this->setError('登录已失效，请重新登录');
         return false;
      }
      
      $permissions = $this->getUserPermissions($uid);
      if($permissions & PERMISSION_JOB_ADMIN_ALL)
         return true;
      
      if(!($permissions & PERMISSION_JOB_ADMIN_ASSIGNED)) {
         $permissions |= PERMISSION_JOB_ADMIN_ASSIGNED;
         if(!$this->setUserPermissions($uid, $permissions)) {
            $this->setError('系统错误');
            return false;
         }
      }
      
      $db = PFactory::getDbo();
      $user = PFactory::getMasterUser();
      
      /* deserted code
      $query = "SELECT COUNT(*) FROM *PREFIX*users_extended AS ue
                WHERE ue.block=0 AND ue.deleted=0 AND ue.permissions & " . $db->quote(PERMISSION_JOB_ADMIN_ALL) . " AND ue.owner=" . $user->id;
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if($db->loadResult()) {
         $this->setError("请解除子账号的全部职位管理权限，再指定负责人！");
         return false;
      }
      */
      
      if(!PCompanyHelper::ownJobId($jobid)) {
         $this->setError("您无权访问该资源！");
         return false;
      }
      
      /* deserted code
      $query = "DELETE FROM *PREFIX*hr_jobmanager WHERE jobid=" . intval($jobid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      */
      
      $query = "INSERT IGNORE INTO *PREFIX*hr_jobmanager (jobid, manager) VALUES (" . intval($jobid) . ", " . $db->quote($uid) . ")";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($uid, array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove($user->id, array('#__jobs_job', '#_jobs_job-'.intval($jobid), '*PREFIX*hr_jobmanager'));

      return true;
   }
   
   public function unsetJobManager($jobid, $uid) {
      if (empty($jobid)) {
         $this->setError("系统错误");
      }
      
      if(!PSession::checkToken('post')) {
         $this->setError('登录已失效，请重新登录');
         return false;
      }
      
      $permissions = $this->getUserPermissions($uid);
      if($permissions & PERMISSION_JOB_ADMIN_ALL)
         return true;
      
      $db = PFactory::getDbo();
      
      if(!PCompanyHelper::ownJobId($jobid)) {
         $this->setError("您无权访问该资源！");
         return false;
      }
      
      $query = "DELETE FROM *PREFIX*hr_jobmanager WHERE jobid=" . intval($jobid) . " AND manager=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($uid, array('*PREFIX*hr_jobmanager')); // used to clear getSubUser caching 
      CacheHelper::triggerRemove(PFactory::getMasterUser()->get('id'), array('#__jobs_job', '#_jobs_job-'.intval($jobid), '*PREFIX*hr_jobmanager'));

      return true;
   }
   
   public function updateSubaccountsNum() {
      $db = PFactory::getDbo();
      $user = PFactory::getMasterUser();
      // update subaccounts number of company
      $query = "UPDATE #__jobs_employer AS je SET je.num_subaccounts=(SELECT COUNT(*) FROM *PREFIX*users_extended WHERE owner=je.user_id AND block=0 AND deleted=0)
                WHERE je.user_id=" . $user->id;
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables
      CacheHelper::triggerRemove($user->id, array('#__jobs_employer'));
      
      return true;
   }

}


